/*
 * Copyright (C), 2013-2018, 上汽集团
 * FileName: QuickTranQuickWinController.java
 * Author:   raolesong
 * Date:     2018年8月18日 上午10:53:35
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.jinznet.transit.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.jinznet.transit.controller.entity.CarOwner;
import com.jinznet.transit.controller.entity.SaleMsg;
import com.jinznet.transit.controller.entity.SalePrize;
import com.jinznet.transit.controller.entity.SalePrizeCondition;
import com.jinznet.transit.controller.vo.Result;
import com.jinznet.transit.service.QuickTranQuickWinService;
import com.jinznet.transit.util.Constant;
import com.jinznet.transit.util.CookieUtil;
import com.jinznet.transit.wx.WXJS;
import com.jinznet.transit.wx.WeChatAccessToken;
import com.jinznet.transit.wx.WeiXinChatUtils;

/**
 * 快运快赢
 * 2018年8月18日 上午10:53:35
 */
@RestController
public class QuickTranQuickWinController {
	
	private static String jdTicket100 = "100";
	
	private static String jdTicket200 = "200";
	
	private static String JSAPITICKET = "jsApiTicket";
	
	
	private static HashMap<Integer,Integer> luckRuleMap = new HashMap<Integer,Integer>();
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	static{
		luckRuleMap.put(3, 30);
		luckRuleMap.put(4, 30);
		luckRuleMap.put(5, 100);
		luckRuleMap.put(6, 100);
	}
	
	@Resource
	private QuickTranQuickWinService quickTranQuickWinService;
	
	@RequestMapping("/index")
	public ModelAndView indexNew(HttpServletRequest request,HttpServletResponse response) throws Exception{
//本地测试用		
//CookieUtil.addCookie(response, Constant.COOKIT_SALE_OPENID,"11111", CookieUtil.MAXAGE, null); 
		
		return new ModelAndView("/index-new.ftl");
	}
	
	
	@RequestMapping("/showCarOwner")
	public ModelAndView showCarOwner(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("/car-owner.ftl");
	}
	
	@RequestMapping("/saveCarOwner")
	public ModelAndView saveCarOwner(HttpServletRequest request,HttpServletResponse response){
		CarOwner vo = new CarOwner();
		Map<String,String[]> map = request.getParameterMap();
		logger.info("saveCarOwner : " + map);
		vo.setName(map.get("name")[0]); //解决中文乱码
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			vo.setBuyCarTime(sdf.parse(request.getParameter("buyCarTime")));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		vo.setCreateTime(new Date());
		String openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		vo.setOpenId(openid);
		vo.setPhone(request.getParameter("phone"));
		vo.setVin(request.getParameter("vin"));
		try{
			quickTranQuickWinService.saveCarOwnerInfo(vo);
		}catch(Exception e) {
			return new ModelAndView("redirect:/showError.htm?submitType=2");
		}
		return new ModelAndView("redirect:/saveCarOwnerSuc.htm");
	}
	
	@RequestMapping("/saveCarOwnerSuc")
	public ModelAndView saveCarOwnerSuc(){
		return new ModelAndView("/car-owner-suc.ftl");
	}
	

	@RequestMapping("/showSaleMsg")
	public ModelAndView showSaleMsg(HttpServletRequest request){
		ModelAndView view = new ModelAndView("/sale-msg.ftl");
		String sale_openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		SaleMsg vo = quickTranQuickWinService.getSaleMsgByOpenId(sale_openid);
		if(vo!=null){
			view.addObject("vo", vo);
		}else{
			view.addObject("vo", new SaleMsg());
		}
		return view;
	}
	
	@RequestMapping("/saveSaleMsg")
	public ModelAndView saveSaleMsg(HttpServletRequest request){
		Map<String,String[]> map = request.getParameterMap();
		logger.info("saveSaleMsg : " + map);
		SaleMsg vo = new SaleMsg();
		String sale_openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		vo.setOpenId(sale_openid);
		vo.setRecommendCarName(map.get("recommendCarName")[0]);
		vo.setRecommendCarPhone(request.getParameter("recommendCarPhone"));
		vo.setSaleName(map.get("saleName")[0]);
		vo.setSalePhone(request.getParameter("salePhone"));
		vo.setStoreCity(map.get("storeCity")[0]);
		vo.setStoreName(map.get("storeName")[0]);
		vo.setStoreProvince(map.get("storeProvince")[0]);
		vo.setRecommendCarVin(request.getParameter("recommendCarVin"));
		try{
			quickTranQuickWinService.saveSaleMsg(vo);
		}catch(Exception e) {
			//vin重复
			logger.error("vin重复了============");
			return new ModelAndView("redirect:/showError.htm?submitType=1");
		}
		return new ModelAndView("redirect:/saveSaleMsgSuc.htm");
	}
	
	@RequestMapping("/saveSaleMsgSuc")
	public ModelAndView saveSaleMsgSuc(){
		return new ModelAndView("/sale-msg-suc.ftl");
	}
	
	
	@RequestMapping("/showError")
	public ModelAndView showError(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("/submit-error.ftl").addObject("submitType", request.getParameter("submitType"));
	}
	
	
	@RequestMapping("/rotate")
	public ModelAndView rotate(HttpServletRequest request,HttpServletResponse response){
		String sale_openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		SalePrizeCondition vo = quickTranQuickWinService.getSalePrizeCondition(sale_openid);
		int luckCount = 0;
		if(vo!=null){
			luckCount = vo.getAvailable_num();
		}
		return new ModelAndView("/rotate.ftl").addObject("luckCount",luckCount);
	}
	
	//抽第几次openId 次数-> 存cookite
	//0：中奖了，1:没中，下次继续,2:很遗憾,奖抽完了，3：重复抽奖,4:无抽奖机会
	@RequestMapping("/salePrize")
	@ResponseBody
	public Result salePrize(HttpServletRequest request,HttpServletResponse response){
		
		Result result = new Result();
		String sale_openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		SalePrizeCondition vo = quickTranQuickWinService.getSalePrizeCondition(sale_openid);
		if(vo == null || vo.getAvailable_num()<=0){
			result.setCode(4);
			result.setMsg("无抽奖机会");
			return result;
		}
		
		//先减少抽奖机会
		quickTranQuickWinService.reduceSalePrizeCondition(sale_openid);
		logger.info(sale_openid+"已用了一次抽奖机会");
		
		int luckIndex = 1;
		if(vo!=null){
			luckIndex = vo.getUse_num()+1;
		}
		
		String prizeDes = "0";
		if(luckIndex<3){
			prizeDes = "0";
		}else if(luckIndex>=3 && luckIndex<=5){
			prizeDes = jdTicket100;
		}else{
			prizeDes = jdTicket200;
		}
		
		if(luckIndex<3){
			//抱歉，没中
			result.setCode(1);
			result.setMsg("没中，下次继续");
			if(luckIndex == 1){
				quickTranQuickWinService.doLuckPrize(sale_openid,prizeDes);
			}
			return result;
		}
		
		List<SalePrize> list = quickTranQuickWinService.getSalePrizeList(sale_openid,prizeDes,null);
		if(list!=null && list.size()>0){
			//第3，4，5抽100的，第6抽200的（  中了100，还可以继续中200 )
			if(luckIndex<=5){
				result.setCode(1);
				result.setMsg("没中，下次继续");
			}else{
				result.setCode(3);
				result.setMsg("重复抽奖");
			}
			return result;
		}
		
		
		//抽奖算法
		if(getPrizeChance(luckRuleMap.get(luckIndex))){
			if(quickTranQuickWinService.doLuckPrize(sale_openid,prizeDes)){
				result.setMsg("恭喜您,中奖了");
				result.setData(prizeDes);
			}else{
				//奖抽完
				result.setCode(2);
				result.setMsg("很遗憾,奖抽完了");
			}
		}else{
			//抱歉，没中
			result.setCode(1);
			result.setMsg("没中，下次继续");
		}
		return result;
	}
	
	
	
	@RequestMapping("/getSalePrizeList")
	@ResponseBody
	public Result getSalePrizeList(HttpServletRequest request,HttpServletResponse response){
		Map<String,String[]> map = request.getParameterMap();
		logger.info("getSalePrizeList : " + map);
		Result result = new Result();

		String name = null;
		if(map.containsKey("name")){
			name = map.get("name")[0];
		}
		List<SalePrize> list = quickTranQuickWinService.getSalePrizeList(null,null,name);
		result.setData(list);
		return result;
	}
	
	
	@RequestMapping("/showNewRule")
	public ModelAndView showNewRule(){
		return new ModelAndView("/rule-new.ftl");
	}
	
	
	@RequestMapping("/giftList")
	public ModelAndView giftList(){
		return new ModelAndView("/gift-list.ftl");
	}
	
	
	@RequestMapping("/contestList")
	public ModelAndView contestList(){
		return new ModelAndView("/contest-list.ftl");
	}
	
	@RequestMapping("/contestDetail")
	public ModelAndView contestDetail(){
		return new ModelAndView("/contest-detail.ftl");
	}

	
	@RequestMapping("/giftAddress")
	public ModelAndView showSalePrizeAddress(HttpServletRequest request){
		String prizeDes = request.getParameter("prizeDes");
		return new ModelAndView("/gift-address.ftl").addObject("prizeDes", prizeDes);
	}
	
	
	@RequestMapping("/saveGiftAddress")
	public ModelAndView saveGiftAddress(HttpServletRequest request,HttpServletResponse response){
		Map<String,String[]> map = request.getParameterMap();
		logger.info("saveSalePrizeAddress : " + map);
		
		String sale_openid = CookieUtil.getCookieByKey(request, Constant.COOKIT_SALE_OPENID);
		String prizeDes =  map.get("prizeDes")[0];
		String province =  map.get("province")[0];
		String city =  map.get("city")[0];
		String address =  map.get("address")[0];
		
		quickTranQuickWinService.setSalePrizeAddress(sale_openid, prizeDes, province, city, address);
		return new ModelAndView("redirect:/saveGiftAddressSuc.htm");
	}
	
	
	@RequestMapping("/saveGiftAddressSuc")
	public ModelAndView saveGiftAddressSuc(){
		return new ModelAndView("/gift-address-suc.ftl");
	}
	
	
	@RequestMapping(value="/getCode",method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView getCode(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		logger.info("getCode返回的参数 : " + JSONObject.toJSONString(request.getParameterMap()));
		if(request.getParameterMap().containsKey("code")){
			String code = request.getParameter("code");
			WeChatAccessToken vo = WeiXinChatUtils.getAccessToken(code);
			CookieUtil.addCookie(response, Constant.COOKIT_SALE_OPENID, vo.getOpenid(), CookieUtil.MAXAGE, null);
			logger.info("成功存入openId到cookie==========" +vo.getOpenid() );
		}else{
			logger.error("获取code失败===============");
		}
		
//		//微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp，nonce参数
//        String signature = request.getParameter("signature");
//        //时间戳
//        String timestamp = request.getParameter("timestamp");
//        //随机数
//        String nonce = request.getParameter("nonce");
//        //随机字符串
//        String echostr = request.getParameter("echostr");
//
//        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
//            logger.info("[signature: "+signature + "]<-->[timestamp: "+ timestamp+"]<-->[nonce: "+nonce+"]<-->[echostr: "+echostr+"]");
//            response.getOutputStream().println(echostr);
//        }
		
        return new ModelAndView("redirect:/index.htm");
	}
	
	
	
	
	
	//获取中奖机会
	private boolean getPrizeChance(int seed){
		Random random = new Random();
		int r = random.nextInt(100);
		if(r<=seed){
			return true;
		}
		return false;
	}

}
